$(function() {
	initTree();
});

// ======================初始化树结构========================
var modalSetting = {
	edit : {
		enable : true,
		showRemoveBtn : false,
		showRenameBtn : false,
	},
	data : {
		simpleData : {
			enable : true,
			idKey : "id",
			pIdKey : "parentId",
			rootParentId : 0
		}
	},
	view : {
		showLine : true
	},
	check : {
		enable : true,
		chkboxType : {
			"Y" : "ps",
			"N" : "ps"
		}
	},
	callback : {
		onClick : setId,
		onCheck : getCheckedPart
	}
};
var partIds = [];
function getCheckedPart(e, treeId, treeNode) {
	var treeObj = $.fn.zTree.getZTreeObj("dgpTree");
	var nodes = treeObj.getCheckedNodes(true);
	if (nodes.length == 0) {
		return;
	}
	partIds = getPartIds(nodes);

};
function getPartIds(nodes) {
	// 只显示前面9个
	var j = 0;
	for (var i = 0; i < nodes.length; i++) {
		if (nodes[i].ownAttr == 'part') {
			j++;
			if (j == 9) {
				break;
			}
			partIds.push(nodes[i].id);

		}
	}
	return partIds;
};
function setId(e, treeId, treeNode) {
	var attr = treeNode.ownAttr;
	$("#ownAttr").val(attr);
	$("#clickId").val(treeNode.id);
	var id = $("#clickId").val();
	// 根节点
	if (attr == undefined) {
		attr = 'root';
	}
	// showBindPart(id, attr);
	// showUnbindPart(id, attr);
}
function initTree() {
	var primaryNode = [];
	var url = window.rootPath + '/ui/dgp/initTree';
	jQuery.ajax({
		url : url,
		cache : false,
		type : "get",
		data : '',
		dataType : "json",
		contentType : 'application/json;charset=utf-8',// 解决返回数据中的中文乱码问题
		success : function(data) {
			primaryNode.push({
				"id" : '0',
				"name" : '根节点',
				"open" : true,
				"isParent" : true
			});

			for (var i = 0; i < data.nodes.length; i++) {
				var dNode = data.nodes[i];
				primaryNode.push(dNode);
				$.fn.zTree.init($("#dgpTree"), modalSetting, primaryNode);
				if (dNode.listG != undefined) {
					var gNode = dNode.listG;
					for (var j = 0; j < gNode.length; j++) {
						primaryNode.push(gNode[j]);
						$.fn.zTree.init($("#dgpTree"), modalSetting,
								primaryNode);

						if (gNode[j].listP != undefined) {
							var pNode = gNode[j].listP;
							for (var k = 0; k < pNode.length; k++) {
								primaryNode.push(pNode[k]);
								$.fn.zTree.init($("#dgpTree"), modalSetting,
										primaryNode);
							}
						}
					}

				}
			}
		}

	});

};